<template>
  <view class="profile-container">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <text class="nav-title">编辑个人信息</text>
      <view class="nav-right" @click="saveProfile">
        <text class="save-btn" :class="{ disabled: loading }">保存</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 头像设置 -->
      <view class="form-item avatar-item">
        <text class="form-label">头像</text>
        <view class="avatar-section" @click="changeAvatar">
          <image class="avatar" :src="profileForm.avatar || '/static/logo.png'" mode="aspectFill" />
          <view class="avatar-overlay">
            <text class="camera-icon">📷</text>
          </view>
        </view>
      </view>

      <!-- 昵称设置 -->
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input 
          class="form-input" 
          v-model="profileForm.nickName" 
          placeholder="请输入昵称"
          maxlength="50"
        />
      </view>

      <!-- 邮箱卡片 -->
      <view class="form-item email-item">
        <text class="form-label">邮箱</text>
        <view class="email-display">
          <text class="email-text">{{ userInfo?.email || '未设置邮箱' }}</text>
        </view>
      </view>

      <!-- 在线状态设置 -->
      <view class="form-item">
        <text class="form-label">在线状态</text>
        <view class="status-options">
          <view 
            class="status-option" 
            :class="{ active: profileForm.status === 1 }"
            @click="setStatus(1)"
          >
            <view class="status-dot online"></view>
            <text class="status-text">在线</text>
          </view>
          <view 
            class="status-option" 
            :class="{ active: profileForm.status === 2 }"
            @click="setStatus(2)"
          >
            <view class="status-dot busy"></view>
            <text class="status-text">忙碌</text>
          </view>
          <view 
            class="status-option" 
            :class="{ active: profileForm.status === 0 }"
            @click="setStatus(0)"
          >
            <view class="status-dot offline"></view>
            <text class="status-text">离线</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载遮罩 -->
    <view class="loading-overlay" v-if="loading">
      <view class="loading-spinner"></view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { UserAPI } from '@/utils/api'
import { AuthUtils } from '@/utils/auth'

// 响应式数据
const loading = ref(false)
const userInfo = ref(null)
const profileForm = ref({
  nickName: '',
  avatar: '',
  status: 1 // 默认在线状态
})

// 初始化用户信息
const initUserInfo = () => {
  const userData = AuthUtils.getUserInfo()
  if (userData) {
    userInfo.value = userData
    profileForm.value = {
      nickName: userData.nickName || '',
      avatar: userData.avatar || '',
      status: userData.status || 1
    }
  }
}

// 返回上一页
const goBack = () => {
   uni.switchTab({
    url: '/pages/message'
  })
}

// 设置在线状态
const setStatus = (status: number) => {
  profileForm.value.status = status
}

// 更换头像
const changeAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 这里应该上传图片到服务器，暂时使用本地路径
      profileForm.value.avatar = res.tempFilePaths[0]
      
      uni.showToast({
        title: '头像已选择，请点击保存',
        icon: 'none'
      })
    },
    fail: (err) => {
      console.error('选择头像失败:', err)
      uni.showToast({
        title: '选择头像失败',
        icon: 'none'
      })
    }
  })
}

// 保存个人信息
const saveProfile = async () => {
  if (loading.value) return
  
  // 验证昵称
  if (!profileForm.value.nickName.trim()) {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none'
    })
    return
  }
  
  if (profileForm.value.nickName.length > 50) {
    uni.showToast({
      title: '昵称不能超过50个字符',
      icon: 'none'
    })
    return
  }
  
  loading.value = true
  
  try {
    const updateData: any = {
      nickName: profileForm.value.nickName.trim(),
      status: profileForm.value.status
    }
    
    // 如果头像有变化，添加到更新数据中
    if (profileForm.value.avatar) {
      updateData.avatar = profileForm.value.avatar
    }
    
    const response = await UserAPI.updateProfile(updateData)
    
    if (response.code === 200 && response.data) {
      // 更新本地存储的用户信息
      AuthUtils.updateUserInfo(response.data)
      
      // 调用获取用户信息接口更新完整的用户信息
      try {
        const userInfoResponse = await UserAPI.getUserInfo()
        if (userInfoResponse.code === 200 && userInfoResponse.data) {
          // 更新本地存储的完整用户信息
          const currentToken = AuthUtils.getToken()
          if (currentToken) {
            AuthUtils.saveUserInfo(currentToken, {
              userId: userInfoResponse.data.userId,
              nickName: userInfoResponse.data.nickName,
              avatar: userInfoResponse.data.avatar,
              status: userInfoResponse.data.status,
              email: userInfoResponse.data.email
            })
          }
        }
      } catch (error) {
        console.error('获取最新用户信息失败:', error)
      }
      
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    }
  } catch (error: any) {
    console.error('保存个人信息失败:', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 页面挂载时初始化
onMounted(() => {
  initUserInfo()
})
</script>

<style scoped>
.profile-container {
  height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
}

/* 导航栏样式 */
.navbar {
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #e5e5e5;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 48rpx;
  color: #007aff;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

.nav-right {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn {
  font-size: 32rpx;
  color: #007aff;
  font-weight: 500;
}

.save-btn.disabled {
  color: #cccccc;
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding: 40rpx 30rpx;
}

/* 表单项样式 */
.form-item {
  background-color: #ffffff;
  margin-bottom: 30rpx;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
}

.form-label {
  font-size: 32rpx;
  color: #333333;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: block;
}

.form-input {
  width: 100%;
  font-size: 32rpx;
  color: #333333;
  padding: 20rpx 0;
  border: none;
  outline: none;
  background: transparent;
}

.form-input::placeholder {
  color: #999999;
}

/* 头像设置样式 */
.avatar-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 邮箱卡片样式 */
.email-item {
  background-color: #f8f9fa;
  border: 1rpx solid #e5e5e5;
}

.email-display {
  padding: 20rpx 0;
}

.email-text {
  font-size: 32rpx;
  color: #666666;
  font-weight: 400;
}

.avatar-section {
  position: relative;
  cursor: pointer;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 2rpx solid #e5e5e5;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-section:active .avatar-overlay {
  opacity: 1;
}

.camera-icon {
  font-size: 36rpx;
  color: #ffffff;
}

/* 状态选项样式 */
.status-options {
  display: flex;
  gap: 30rpx;
}

.status-option {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 15rpx;
  transition: all 0.3s ease;
}

.status-option.active {
  border-color: #007aff;
  background-color: #f0f8ff;
}

.status-dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 10rpx;
  margin-right: 15rpx;
}

.status-dot.online {
  background-color: #34c759;
}

.status-dot.busy {
  background-color: #ff9500;
}

.status-dot.offline {
  background-color: #8e8e93;
}

.status-text {
  font-size: 28rpx;
  color: #333333;
}

.status-option.active .status-text {
  color: #007aff;
  font-weight: 500;
}

/* 加载遮罩 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #ffffff;
  border-top: 4rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .status-options {
    flex-direction: column;
    gap: 20rpx;
  }
  
  .status-option {
    justify-content: flex-start;
  }
}
</style>